package com.aoxiang.zbox.common.util;

import com.aoxiang.zbox.config.DataSourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class UserDatabaseUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserDatabaseUtil.class);

    public static void createUserDatabase(Long userId) {
        String dbPath = DataSourceConfig.getUserDatabasePath(userId);
        String url = "jdbc:sqlite:" + dbPath;
        try (Connection conn = DriverManager.getConnection(url)) {
            String sql = readSqlFromResource("sql/userData.sql");
            String[] sqlStatements = sql.split(";");
            try (Statement stmt = conn.createStatement()) {
                for (String statement : sqlStatements) {
                    String trimmedStatement = statement.trim();
                    if (!trimmedStatement.isEmpty()) {
                        stmt.executeUpdate(trimmedStatement);  // 执行每条语句
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("创建用户数据库失败", e);
            throw new RuntimeException("创建用户数据库失败", e);
        }
    }

    // 从 classpath 中读取 SQL 文件
    private static String readSqlFromResource(String resourcePath) {
        InputStream inputStream = UserDatabaseUtil.class.getClassLoader().getResourceAsStream(resourcePath);
        if (inputStream == null) {
            throw new RuntimeException("资源文件不存在: " + resourcePath);
        }

        Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name());
        StringBuilder contentBuilder = new StringBuilder();
        while (scanner.hasNextLine()) {
            contentBuilder.append(scanner.nextLine()).append("\n");
        }
        return contentBuilder.toString();
    }

    public static void deleteUserDatabase(String userDatabasePath) {
        // 删除文件
        try {
            Path path = Paths.get(userDatabasePath);
            Files.deleteIfExists(path);
        } catch (Exception e) {
            LOGGER.error("删除用户数据库失败", e);
        }
    }
}
